import java.util.*;

/**
 * @program: leetcode001
 * @author: JCM
 * @create: 2022-11-18 10:48
 * @description:
 **/
public class leetCode001 {
    public static void main(String[] args) {
        int[] nums = {12,3,4,1,5,6,4,8,7,0};
        int target = 11;
        //int[] ret = twoSum1(nums,target);
        int[] ret = twoSum2(nums,target);
        System.out.println(Arrays.toString(ret));
    }

    //1. 暴力枚举
    public static int[] twoSum1(int[] nums, int target) {
        int[] ans = {-1,-1};
        for(int i = 0 ; i< nums.length-1; i++) {
            for(int j = i+1;j < nums.length; j++) {
                if(nums[i]+nums[j] == target) {
                    ans[0] = i;
                    ans[1] = j;
                    return ans;
                }
            }
        }
        return ans;
    }
    //2. 哈希表
    public static int[] twoSum2(int[] nums, int target) {
        Map<Integer,Integer> hashtable = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (hashtable.containsKey(target - nums[i])) {
                return new int[] {
                        hashtable.get(target-nums[i]),i
                };
            }
            hashtable.put(nums[i],i);
        }
        return new int[0];
    }
}
